package com.heima.search.service.impl;

import com.heima.common.constants.search.SearchConstants;
import com.heima.es.service.EsService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.search.dtos.UserSearchDTO;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mrchen
 * @date 2022/7/17 10:33
 */
@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {
    @Autowired
    EsService<SearchArticleVO> esService;
    @Value("${file.minio.readPath}")
    String readPath;
    @Value("${file.oss.web-site}")
    String webSite;

    @Autowired
    ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDTO dto) {
        // 参数校验
        String searchWords = dto.getSearchWords();
        if (StringUtils.isBlank(searchWords)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        dto.setUserId(user==null?null:user.getId());
        apUserSearchService.insert(dto);

        if (dto.getMinBehotTime()==null){
            dto.setMinBehotTime(new Date());
        }
        if(dto.getPageSize()<=0){
            dto.setPageSize(10);
        }
        // 1. 构建搜索条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        //   1.1 创建bool条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //   1.2 将 分词查询关键字加入到bool条件 must
        boolQuery.must(QueryBuilders.matchQuery("title",dto.getSearchWords()));
        //   1.3 将 查询发布时间小于最小时间  加入到bool条件  filter
        boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        builder.query(boolQuery);
        //   1.4 设置分页  size
        builder.size(dto.getPageSize());
        //   1.5 设置按照发布时间降序排序
        builder.sort("publishTime", SortOrder.DESC);
        //   1.6 设置文章标题 高亮处理
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");// 哪个字段高亮
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        builder.highlighter(highlightBuilder);
        // 2. 执行搜索
        PageResponseResult searchResult = esService.search(builder, SearchArticleVO.class, SearchConstants.ARTICLE_INDEX_NAME);
        List<SearchArticleVO> list= (List<SearchArticleVO>)searchResult.getData();
        // 3. 封装响应结果
        for (SearchArticleVO searchArticleVO : list) {
            String images = searchArticleVO.getImages();
            if (StringUtils.isNotBlank(images)){
                // url1.jpg,url2.jpg,url3.jpg
                images = Arrays.stream(images.split(","))
                            .map(url -> webSite + url)
                            .collect(Collectors.joining(","));
                searchArticleVO.setImages(images);
            }
            searchArticleVO.setStaticUrl(readPath + searchArticleVO.getStaticUrl());
        }
        return searchResult;
    }

    @Override
    public void saveArticle(SearchArticleVO article) {
        esService.save(article,SearchConstants.ARTICLE_INDEX_NAME);
    }

    @Override
    public void deleteArticle(String articleId) {
        esService.deleteById(articleId,SearchConstants.ARTICLE_INDEX_NAME);
    }
}
